package com.fcgzs.springboot.cfg;
//安全框架配置类
import com.fcgzs.springboot.handler.AuthenticationEntryPointHandler;
import com.fcgzs.springboot.handler.SecurityAccessDeniedHandler;
import com.fcgzs.springboot.handler.SecurityAuthenticationFailureHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;
//导包：2个
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true) //括号内表示：可以使用相关注解
public class MySecutiryConfiguration extends WebSecurityConfigurerAdapter { //继承：安全校验适配器
    //认证失败的处理工具类
    @Resource
    private SecurityAuthenticationFailureHandler securityAuthenticationFailureHandler;
    //匿名访问被拒的处理工具类
    @Resource
    private AuthenticationEntryPointHandler authenticationEntryPointHandler;
    //认证用户无权限被拒的处理工具类
    @Resource
    private SecurityAccessDeniedHandler securityAccessDeniedHandler;
    //业务层
    @Resource
    private MyUserService userService;

    //创建密码工具对象
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder(); //密码加密器
    }
//重写：2个方法
    //用户名和密码校验
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
    }
    //安全配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //跨站请求防护
        http.csrf().disable().headers().frameOptions().sameOrigin();
        http.csrf().disable()
                .formLogin() //表单方式登录
                .loginPage("/index.html") //指定登录页面
                .loginProcessingUrl("/login") //指定登录方法
                .defaultSuccessUrl("/pages/main.html").permitAll() //登陆成功后跳转页面
                .failureHandler(securityAuthenticationFailureHandler) //登陆失败后跳转页面
                .and() //匿名可以访问资源路径
                .authorizeRequests()
                .antMatchers("/index.html","/login","/loginstyle/**","/css/**","/js/**","/img/**","/plugins/**") //指定可访问页面
                .permitAll()
                .anyRequest() //其余所有请求
                .authenticated(); //登录后才能访问
        //异常访问安全框架的处理方式
        http.exceptionHandling().authenticationEntryPoint(authenticationEntryPointHandler).accessDeniedHandler(securityAccessDeniedHandler);
        //退出登录的方法
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/index.html");
    }
}
